import { useCallback, useEffect, useRef, useState } from 'react'
import { useImageStore } from '@/stores/imageStore'
import { useTaskStore } from '@/stores/taskStore'
import { useUIStore } from '@/stores/uiStore'
import { api } from '@/lib/api'
import { ApiClientError } from '@/lib/apiError'
import { withRetry } from '@/lib/retryMechanism'
import type {
    Dataset,
    ImageData,
    ImageMetadata,
    Task,
    TaskResult,
    TaskParams,
    CreateTaskRequest,
    UpdateTaskRequest
} from '@/types'
import type { CreateDatasetRequest, UpdateDatasetRequest } from '@/types/dataset'

// API调用选项
interface ApiCallOptions {
    enableCache?: boolean
    enableRetry?: boolean
    showLoading?: boolean
    showNotification?: boolean
    retryAttempts?: number
    cacheTimeout?: number
    loadingComponent?: string
}

// API调用结果
interface ApiCallResult<T> {
    data: T | null
    loading: boolean
    error: ApiClientError | null
    refetch: () => Promise<void>
}

// 默认选项
const defaultOptions: ApiCallOptions = {
    enableCache: true,
    enableRetry: true,
    showLoading: true,
    showNotification: true,
    retryAttempts: 3,
    cacheTimeout: 5 * 60 * 1000, // 5分钟
}

export const useApi = () => {
    const imageStore = useImageStore()
    const taskStore = useTaskStore()
    const uiStore = useUIStore()

    // 用于取消请求的引用
    const abortControllerRef = useRef<AbortController | null>(null)

    // 清理函数
    useEffect(() => {
        return () => {
            if (abortControllerRef.current) {
                abortControllerRef.current.abort()
            }
        }
    }, [])

    // 通用API调用包装器
    const makeApiCall = useCallback(async <T>(
        apiCall: () => Promise<T>,
        options: ApiCallOptions = {}
    ): Promise<T> => {
        const opts = { ...defaultOptions, ...options }

        // 设置加载状态
        if (opts.showLoading && opts.loadingComponent) {
            uiStore.setComponentLoading(opts.loadingComponent, true)
        }

        try {
            let result: T

            if (opts.enableRetry) {
                result = await withRetry(apiCall, { maxAttempts: opts.retryAttempts || 3 })
            } else {
                result = await apiCall()
            }

            // 显示成功通知
            if (opts.showNotification) {
                uiStore.addNotification({
                    type: 'success',
                    title: '操作成功',
                    message: 'API调用成功完成',
                    duration: 2000
                })
            }

            return result

        } catch (error) {
            const apiError = error instanceof ApiClientError ? error : new ApiClientError(
                error instanceof Error ? error.message : '未知错误',
                'API_CALL_ERROR'
            )

            // 显示错误通知
            if (opts.showNotification) {
                uiStore.addNotification({
                    type: 'error',
                    title: 'API调用失败',
                    message: apiError.message,
                    duration: 5000
                })
            }

            throw apiError

        } finally {
            // 清除加载状态
            if (opts.showLoading && opts.loadingComponent) {
                uiStore.setComponentLoading(opts.loadingComponent, false)
            }
        }
    }, [uiStore])

    // 数据集相关API
    const datasets = {
        // 加载所有数据集
        loadAll: useCallback(async (options?: ApiCallOptions) => {
            return makeApiCall(
                () => imageStore.loadDatasets(options?.enableCache === false),
                { ...options, loadingComponent: 'datasets' }
            )
        }, [imageStore, makeApiCall]),

        // 加载单个数据集
        loadOne: useCallback(async (datasetId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => imageStore.loadDataset(datasetId, options?.enableCache === false),
                { ...options, loadingComponent: 'dataset' }
            )
        }, [imageStore, makeApiCall]),

        // 加载数据集统计
        loadStats: useCallback(async (datasetId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => imageStore.loadDatasetStats(datasetId, options?.enableCache === false),
                { ...options, loadingComponent: 'dataset-stats' }
            )
        }, [imageStore, makeApiCall]),

        // 创建数据集
        create: useCallback(async (datasetData: CreateDatasetRequest, options?: ApiCallOptions) => {
            return makeApiCall(
                () => api.createDataset(datasetData),
                { ...options, enableCache: false, loadingComponent: 'dataset-create' }
            )
        }, [makeApiCall]),

        // 更新数据集
        update: useCallback(async (datasetId: string, updates: UpdateDatasetRequest, options?: ApiCallOptions) => {
            return makeApiCall(
                () => api.updateDataset(datasetId, updates),
                { ...options, enableCache: false, loadingComponent: 'dataset-update' }
            )
        }, [makeApiCall]),

        // 删除数据集
        delete: useCallback(async (datasetId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => api.deleteDataset(datasetId),
                { ...options, enableCache: false, loadingComponent: 'dataset-delete' }
            )
        }, [makeApiCall])
    }

    // 图像相关API
    const images = {
        // 加载图像数据
        loadData: useCallback(async (imageId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => imageStore.loadImageData(imageId, options?.enableCache === false),
                { ...options, loadingComponent: 'image-data' }
            )
        }, [imageStore, makeApiCall]),

        // 加载图像元数据
        loadMetadata: useCallback(async (imageId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => imageStore.loadImageMetadata(imageId, options?.enableCache === false),
                { ...options, loadingComponent: 'image-metadata' }
            )
        }, [imageStore, makeApiCall]),

        // 上传图像
        upload: useCallback(async (datasetId: string, files: File[], options?: ApiCallOptions) => {
            return makeApiCall(
                () => api.uploadImages(datasetId, files),
                { ...options, enableCache: false, loadingComponent: 'image-upload' }
            )
        }, [makeApiCall]),

        // 删除图像
        delete: useCallback(async (imageIds: string[], options?: ApiCallOptions) => {
            return makeApiCall(
                () => api.deleteImages(imageIds),
                { ...options, enableCache: false, loadingComponent: 'image-delete' }
            )
        }, [makeApiCall])
    }

    // 任务相关API
    const tasks = {
        // 加载任务列表
        loadAll: useCallback(async (datasetId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => taskStore.loadTasks(datasetId),
                { ...options, loadingComponent: 'tasks' }
            )
        }, [taskStore, makeApiCall]),

        // 创建任务
        create: useCallback(async (taskData: CreateTaskRequest, options?: ApiCallOptions) => {
            return makeApiCall(
                () => taskStore.createTask(taskData),
                { ...options, enableCache: false, loadingComponent: 'task-create' }
            )
        }, [taskStore, makeApiCall]),

        // 更新任务
        update: useCallback(async (taskId: string, updates: UpdateTaskRequest, options?: ApiCallOptions) => {
            return makeApiCall(
                () => taskStore.updateTask(taskId, updates),
                { ...options, enableCache: false, loadingComponent: 'task-update' }
            )
        }, [taskStore, makeApiCall]),

        // 删除任务
        delete: useCallback(async (taskId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => taskStore.deleteTask(taskId),
                { ...options, enableCache: false, loadingComponent: 'task-delete' }
            )
        }, [taskStore, makeApiCall]),

        // 启动任务
        start: useCallback(async (taskId: string, params?: TaskParams, options?: ApiCallOptions) => {
            return makeApiCall(
                () => taskStore.startTask(taskId, params),
                { ...options, enableCache: false, loadingComponent: 'task-start' }
            )
        }, [taskStore, makeApiCall]),

        // 取消任务
        cancel: useCallback(async (taskId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => taskStore.cancelTask(taskId),
                { ...options, enableCache: false, loadingComponent: 'task-cancel' }
            )
        }, [taskStore, makeApiCall]),

        // 重试任务
        retry: useCallback(async (taskId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => taskStore.retryTask(taskId),
                { ...options, enableCache: false, loadingComponent: 'task-retry' }
            )
        }, [taskStore, makeApiCall]),

        // 加载任务结果
        loadResults: useCallback(async (taskId: string, options?: ApiCallOptions) => {
            return makeApiCall(
                () => taskStore.loadTaskResults(taskId),
                { ...options, loadingComponent: 'task-results' }
            )
        }, [taskStore, makeApiCall])
    }

    // 系统相关API
    const system = {
        // 健康检查
        healthCheck: useCallback(async (options?: ApiCallOptions) => {
            return makeApiCall(
                () => api.healthCheck(),
                { ...options, showNotification: false, loadingComponent: 'health-check' }
            )
        }, [makeApiCall])
    }

    // 批量操作
    const batch = {
        // 批量加载数据集和任务
        loadDatasetWithTasks: useCallback(async (datasetId: string, options?: ApiCallOptions) => {
            return makeApiCall(async () => {
                // 并行加载数据集信息和任务列表
                const [dataset, tasks] = await Promise.all([
                    imageStore.loadDataset(datasetId),
                    taskStore.loadTasks(datasetId)
                ])

                return { dataset, tasks }
            }, { ...options, loadingComponent: 'dataset-with-tasks' })
        }, [imageStore, taskStore, makeApiCall]),

        // 批量加载图像数据和元数据
        loadImageWithMetadata: useCallback(async (imageId: string, options?: ApiCallOptions) => {
            return makeApiCall(async () => {
                // 并行加载图像数据和元数据
                const [imageData, metadata] = await Promise.all([
                    imageStore.loadImageData(imageId),
                    imageStore.loadImageMetadata(imageId)
                ])

                return { imageData, metadata }
            }, { ...options, loadingComponent: 'image-with-metadata' })
        }, [imageStore, makeApiCall])
    }

    // 缓存管理
    const cache = {
        // 清除所有缓存
        clearAll: useCallback(() => {
            imageStore.clearCache()
            uiStore.addNotification({
                type: 'info',
                title: '缓存已清除',
                message: '所有缓存数据已清除',
                duration: 2000
            })
        }, [imageStore, uiStore]),

        // 清除特定类型的缓存
        clear: useCallback((cacheType: 'datasets' | 'images' | 'metadata' | 'stats') => {
            imageStore.clearCache(cacheType)
            uiStore.addNotification({
                type: 'info',
                title: '缓存已清除',
                message: `${cacheType} 缓存已清除`,
                duration: 2000
            })
        }, [imageStore, uiStore])
    }

    return {
        datasets,
        images,
        tasks,
        system,
        batch,
        cache,
        // 直接访问API客户端（用于特殊情况）
        client: api
    }
}

// 专用Hook：用于特定API调用的状态管理
export const useApiCall = <T>(
    apiCall: () => Promise<T>,
    dependencies: unknown[] = [],
    options: ApiCallOptions = {}
): ApiCallResult<T> => {
    const [data, setData] = useState<T | null>(null)
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<ApiClientError | null>(null)
    const api = useApi()

    const refetch = useCallback(async () => {
        setLoading(true)
        setError(null)

        try {
            const result = await apiCall()
            setData(result)
        } catch (err) {
            setError(err as ApiClientError)
        } finally {
            setLoading(false)
        }
    }, [apiCall, options])

    useEffect(() => {
        refetch()
    }, dependencies)

    return { data, loading, error, refetch }
}

export default useApi